<?php

namespace api\modules\v1\controllers\task;

use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use common\helpers\ResultHelper;
use common\helpers\UploadHelper;
use common\models\task\TaskProList;
use common\models\task\TaskList;
use common\queues\TaskSettlementJob;
use Yii;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;

/**
 * 默认控制器
 *
 * Class IndexController
 * @package api\modules\v1\controllers
 * @property \yii\db\ActiveRecord $modelClass
 * @author  
 */
class TaskListController extends OnAuthController
{
    public $modelClass = TaskList::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    // protected $authOptional = ['index'];

    /**
     * @return string|\yii\data\ActiveDataProvider
     */

    public function actionIndex()
    {
        $status = Yii::$app->request->get('status',0);
        $member_id = Yii::$app->user->identity->member_id;
        return new ActiveDataProvider([
            'query' => $this->modelClass::find()
                ->where(['status' => $status])
                ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
                ->andFilterWhere(['member_id' => $member_id])
                ->orderBy('id desc')
                ->with('taskProList')
                ->asArray(),
            'pagination' => [
                'pageSize' => $this->pageSize,
                'validatePage' => false, // 超出分页不返回data
            ],
        ]);
    }

    public function actionReceiveTask()
    {
        $id = Yii::$app->request->post('id');
        $member_id = Yii::$app->user->identity->member_id;

        $model = new TaskList();
        $model->member_id = $member_id;
        $model->task_id =  $id;
        if($model->add()){
            return true;
        }else{
            return ResultHelper::json(422, $this->getError($model));
        }
    }

    public function actionTaskOrderSubmit()
    {
        $id = Yii::$app->request->post('id');
        $member_id = Yii::$app->user->identity->member_id;
        $model = TaskList::find()->where(['id'=>$id,'member_id'=>$member_id])->one();
        if(!$model){
            return ResultHelper::json(422, 'error');
        }
        $model->status = 1;
        if ($model->save()) {
            Yii::$app->queue->push(new TaskSettlementJob([
                'task' => $model
            ]));
            return true;
        } else {
            return ResultHelper::json(422, $this->getError($model));
        }

    }
}
